﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Coleotrack.Areas.Admin.Models;
using Coleotrack.Core.Helper;
using Coleotrack.Data;
using Coleotrack.Models;
using Coleotrack.Service;
using Coleotrack.Service.Contracts;

namespace Coleotrack.Areas.Admin.Controllers
{
    public class UserController : Controller
    {
        public IUserService UserService
        {
            get;
            private set;
        }

        public UserController(IUserService userService)
        {
            UserService = userService;
        }

        [Authorize]
        public ActionResult Index()
        {
            IEnumerable<User> users = UserService.AllActive();
            if (Request.IsAjaxRequest())
            {
                return View("_List", users);
            }
            else
            {
                return View(users);
            }
        }

        [Authorize, HttpGet]
        public ActionResult Create()
        {
            var model = new UserViewModel(UserService.GetAllRoles());
            return View(model);
        }

        [Authorize, HttpPost]
        public ActionResult Create(User user, string password, string passwordConfirmation)
        {
            try
            {
                if (!ValidateUser(user, password, passwordConfirmation))
                {
                    return View(new UserViewModel(UserService.GetAllRoles()));
                }

                user.Password = password.Md5();
                user.Created = DateTime.Now;

                UserService.Insert(user);

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return View(new UserViewModel(UserService.GetAllRoles()));
            }
        }

        [HttpPost, Authorize]
        public ActionResult Delete(ICollection<int> id)
        {
            foreach (var deleteId in id)
            {
                UserService.Find(deleteId).Active = false;
            }

            return RedirectToAction("Index");
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            var model = new UserViewModel(UserService.GetAllRoles());
            model.User = UserService.Find(id);

            return View(model);
        }

        [HttpPost, Authorize]
        public ActionResult Edit(FormCollection collection, int id, string password, string passwordConfirmation)
        {
            User user = UserService.Find(id);
            UpdateModel<User>(user, "User");

            if (!ValidateUser(user, password, passwordConfirmation))
            {
                UserService.Evict(user);
                return View();
            }

            try
            {
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return View("Error");
            }
        }

        private bool ValidateUser(User user, string password, string passwordConfirm)
        {
            if (!user.IsValid())
            {
                foreach (var ruleViolation in user.GetRuleViolations())
                {
                    ModelState.AddModelError(ruleViolation.PropertyName, ruleViolation.ErrorMessage);
                }
            }

            if (password != passwordConfirm)
            {
                ModelState.AddModelError("_Form", "Password and the confirmation should be equal.");
            }

            if (UserService.All().Any(x => x.Name.Equals(user.Name) && x.Id != user.Id))
            {
                ModelState.AddModelError("Name", "User with the same name already exists.");
            }

            return ModelState.IsValid;
        }
    }
}
